package com.eightbears.beboy.ui.user.activity;

import android.app.Activity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.eightbears.beboy.R;
import com.eightbears.beboy.SplashActivity;
import com.eightbears.beboy.base.BaseActivity;
import com.eightbears.beboy.base.alipay.PayResult;
import com.eightbears.beboy.base.util.CommonAPI;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.GsonUtil;
import com.eightbears.beboy.base.util.InputMethodUtils;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.ShowToast;
import com.eightbears.beboy.base.util.okhttp.OkHttpUtils;
import com.eightbears.beboy.base.util.okhttp.builder.PostFormBuilder;
import com.eightbears.beboy.base.util.okhttp.callback.StringCallback;
import com.eightbears.beboy.base.view.SwipeBackLayout;
import com.eightbears.beboy.base.view.dialog.DefaultDialog;
import com.eightbears.beboy.base.view.popupwindow.PasswordPayPopup;
import com.eightbears.beboy.entity.PayDrawInfoEntity;
import com.eightbears.beboy.entity.PayInfoEntity;
import com.eightbears.beboy.entity.ProfitEntity;
import com.eightbears.beboy.entity.UserEntity;
import com.eightbears.beboy.entity.UserInfoEntity;
import com.eightbears.beboy.entity.status.Status_Error;
import com.eightbears.beboy.ui.login.ForgetActivity;
import com.pnikosis.materialishprogress.ProgressWheel;
import com.socks.library.KLog;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.eightbears.beboy.base.util.CommonAPI.CONNECTION_STATUS_SUCCESS;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER;
import static com.eightbears.beboy.base.util.CommonAPI.URL_DRAW_MONEY;

import static com.eightbears.beboy.ui.user.activity.PaymentActivity.EVENT_MY_PAY;
import static com.eightbears.beboy.ui.user.activity.PaymentActivity.SDK_PAY_FLAG;
import static com.eightbears.beboy.ui.user.activity.TransferActivity.PARAMS_PAY_TRANSFER;
import static com.eightbears.beboy.ui.user.fragment.MyFragment.EVENT_UPDATE_USERINFO;
import static com.eightbears.beboy.ui.user.fragment.RrofitFragment.PROFIT_INFO;
import static com.eightbears.beboy.ui.user.fragment.RrofitFragment.WITHDRAW_MLM;

/**
 * 提现页面
 */

public class DrawMoneyActivity extends BaseActivity {

    public static final String EVENT_DRAW_MONEY = "drawMoney";

    @BindView(R.id.rl_root)
    RelativeLayout rl_root;
    @BindView(R.id.sw_finish)
    SwipeBackLayout sw_finish;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.et_draw_money)
    EditText et_draw_money;
    @BindView(R.id.et_draw_account)
    EditText et_draw_account;
    @BindView(R.id.et_draw_name)
    EditText et_draw_name;
    @BindView(R.id.tv_btn_draw_money)
    TextView tv_btn_draw_money;
    @BindView(R.id.tv_alert_text)
    TextView tv_alert_text;
    @BindView(R.id.view_loading)
    View view_loading;
    @BindView(R.id.tv_loading_text)
    TextView tv_loading_text;
    private UserInfoEntity mUserInfoEntity;
    private String drawMoneyNum;
    private String totalBalance;
    private UserEntity.Shop shop;
    private String drawMoneyName;
    private String drawMoneyAccount;
    private double mRatio;
    private double mMoney;
    private PasswordPayPopup mPasswordPayPopup;
    private String mTotalBalance;
    private PayDrawInfoEntity mPayDrawInfoEntity;
    private String mWithDrawParam;
    private String mDrawRatio;
    private String mDrawLimit;
    private String mTotalMoney;
    private String mRemain_balance;
    private DefaultDialog.Builder mBuilder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_draw_money);
        initView();
        initData();
        initEvent();
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        mBuilder = new DefaultDialog.Builder(mContext);
        mUserInfoEntity = (UserInfoEntity) getExtras().get(EVENT_UPDATE_USERINFO);
        mWithDrawParam = (String) getExtras().get(CommonAPI.WITHDRAW);
        mRemain_balance = (String) getExtras().get(PROFIT_INFO);
        KLog.e(mWithDrawParam);
        KLog.e(mRemain_balance);
        tv_title.setText(R.string.text_profit_take_money);
        tv_loading_text.setText(R.string.text_submit_data_wait);
    }

    @Override
    protected void initData() {
        if (mWithDrawParam.equals(WITHDRAW_MLM)){
            mTotalBalance= mRemain_balance;
            mDrawRatio = mUserInfoEntity.getData().getMlm_ratio();
            mDrawLimit = mUserInfoEntity.getData().getMlm_limit();
            mTotalMoney = getString(R.string.alert_draw_money_tip, mTotalBalance);
        }else{
            mTotalBalance = mUserInfoEntity.getData().getBalance();
            mDrawRatio = mUserInfoEntity.getData().getRatio();
            mDrawLimit = mUserInfoEntity.getData().getLimit();
            mTotalMoney = getString(R.string.alert_draw_money_tip, mTotalBalance);
        }
        String newRatio= Double.valueOf(mDrawRatio)*100+"%";
        String format = String.format(getString(R.string.text_price_ratio),newRatio);
        tv_alert_text.setText(Html.fromHtml(mTotalMoney)+format);
    }

    @Override
    protected void initEvent() {
        sw_finish.setCallBack(new SwipeBackLayout.CallBack() {
            @Override
            public void onFinish() {
                finish();
            }
        });
        et_draw_money.addTextChangedListener(watcher);
    }

    @OnClick(R.id.ll_back)
    void llBack() {
        finish();
    }
    //TODO
    //点击提现
    @OnClick(R.id.tv_btn_draw_money)
    void submitDraw() {
        if (validInput()) {
            InputMethodUtils.closeInputMethod(getApplicationContext(), et_draw_money);
            initPwPopup();
        }
    }

    private boolean validInput() {

        drawMoneyNum = et_draw_money.getText().toString();
        drawMoneyName = et_draw_name.getText().toString();
        drawMoneyAccount = et_draw_account.getText().toString();

        if ("".equals(drawMoneyName.trim())) {
            ShowToast.showShortToast(getString(R.string.text_pay_ali_name));
            return false;
        }

        if ("".equals(drawMoneyAccount.trim())) {
            ShowToast.showShortToast(getString(R.string.text_pay_ali_account));
            return false;
        }

        if ("".equals(drawMoneyNum.trim())) {
            ShowToast.showShortToast(getString(R.string.text_pay_ali_with_draw));
            return false;
        }

        mMoney = Double.parseDouble(drawMoneyNum);
        double balance = Double.parseDouble(mTotalBalance);
        double limit = Double.parseDouble(mDrawLimit.trim());
        mRatio = Double.parseDouble(mDrawRatio);

        if (mMoney < limit) {
            ShowToast.showShortToast(getString(R.string.text_pay_ali_with_draw_info) + limit);
            return false;
        }

        if (mMoney > balance) {
            ShowToast.showShortToast(getString(R.string.text_pay_ali_with_draw_balance));
            return false;
        }
        return true;
    }

    private TextWatcher watcher = new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (s.toString().length() > 0 && Double.parseDouble(s.toString()) > 0) {
                tv_btn_draw_money.setBackgroundColor(getResources().getColor(R.color.text_money_color));
            } else {
                tv_btn_draw_money.setBackgroundColor(getResources().getColor(R.color.text_color_999));
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    };

    private void initPwPopup() {
        if (null == mPasswordPayPopup) {
            mPasswordPayPopup = new PasswordPayPopup((Activity) mContext);
            mPasswordPayPopup.setAccountName(getString(R.string.text_profit_take_money));
            mPasswordPayPopup.setBalance("￥" + drawMoneyNum);
        }
        mPasswordPayPopup.setOnItemClickListener(new PasswordPayPopup.onPasswordPayPopupClickListener() {
            @Override
            public void onItemClick() {
                startLocalActivity((Activity) mContext, ForgetActivity.class, PARAMS_PAY_TRANSFER, PARAMS_PAY_TRANSFER);
            }
        });
        mPasswordPayPopup.setOnClickSurePayListener(new PasswordPayPopup.OnClickSurePayListener() {
            @Override
            public void onClickItem(TextView mTv_sure, ProgressWheel mProgress_wheel, String mPassword) {
//                myPay(mPassword);
                if (TextUtils.isEmpty(mPassword) || mPassword.length() < 6) {
                    ShowToast.showShortToast(getString(R.string.text_user_pay_info));
                    return;
                }
                myPay(mPassword);
            }
        });
        mPasswordPayPopup.showPopupWindow();
    }
    /**
     * 提現
     */
    private void myPay(String password) {
        view_loading.setVisibility(View.VISIBLE);
        mPasswordPayPopup.setTextGoneWheelVisiable();
        PostFormBuilder post = OkHttpUtils.post();
        post.url(URL_DRAW_MONEY);
        post.addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken());
        post.addParams("password", password);
        post.addParams("apply_amount",String.valueOf(mMoney));
        if (mWithDrawParam.equals(WITHDRAW_MLM)){
            post.addParams("type", "2");
        }else{
            post.addParams("type", "1");
        }
        post.addParams("acc", drawMoneyAccount);
        post.addParams("acc_name", drawMoneyName);
        post.build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                view_loading.setVisibility(View.GONE);
                mPasswordPayPopup.setTextVisiableWheelGone();
                mPasswordPayPopup.setTextClear();

                mBuilder.create();
                mBuilder.setTitle(R.string.alert_text);
                mBuilder.setMessage(R.string.text_with_draw_result_info);
                mBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mPasswordPayPopup.dismiss();
                        finish();
                        EventBus.getDefault().post(EVENT_MY_PAY);
                    }
                });
                mBuilder.create().show();
//                                    ShowToast.showShortToast(getString(R.string.text_pay_success));
//                startLocalActivity((Activity) mContext, BuyResultActivity.class, EVENT_MY_PAY, String.valueOf(mMoney));
            }

            @Override
            public void onError(Call call, Exception e) {
                view_loading.setVisibility(View.GONE);
                mPasswordPayPopup.setTextVisiableWheelGone();
                mPasswordPayPopup.setTextClear();
                KLog.e(e.getMessage());
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(DrawMoneyActivity.this, status_error);
            }
        });
    }
}
